package com.group01.community.controller;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.group01.community.entity.ZyCommunity;
import com.group01.community.entity.vo.ZyCommunityVo;
import com.group01.community.service.ZyCommunityService;
import com.group01.community.utils.ResponseResult;
import com.group01.community.utils.ResponseStatus;
import com.group01.community.utils.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 小区  前端控制器
 * </p>
 *
 * @author guoyuan
 * @since 2025-05-01
 */
@Slf4j
@Api(tags = "小区信息")
@RestController
@RequestMapping("/zyCommunity")
public class ZyCommunityController {

    @Autowired
    private ZyCommunityService zyCommunityService;

    /**
     * 分页条件查询小区信息
     * @param communityCode 物业id
     * @return 小区信息
     */
    @ApiOperation("分页条件查询小区信息")
    @GetMapping("/list")
    public ResponseResult<IPage<ZyCommunityVo>> getAllZyCommunityBycommunityCode(int curr, int size, String communityCode, String communityName) {
        try {
            IPage<ZyCommunityVo> communities = zyCommunityService.getCommunityPage(curr, size, communityCode, communityName);
            return new ResponseResult<IPage<ZyCommunityVo>>(ResponseStatus.OK, communities);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseResult<IPage<ZyCommunityVo>>(ResponseStatus.PARAM_ERROR, null);
    }

    /**
     * 查询所有小区信息
     * @return 小区信息
     */
    @ApiOperation("查询所有小区信息")
    @GetMapping("/listAll")
    public ResponseResult<List<ZyCommunity>> getAllZyCommunity() {
        try {
            return new ResponseResult<List<ZyCommunity>>(ResponseStatus.OK, zyCommunityService.list());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseResult<List<ZyCommunity>>(ResponseStatus.INTERNAL_ERROR, null);
    }

    /**
     * 获取小区和楼栋树
     * @return
     */
    @ApiOperation("查询小区楼栋树")
    @GetMapping("/listCommunityAndBuilding")
    public ResponseResult<List<ZyCommunityVo>> getCommunityAndBuildingTree(){
        List<ZyCommunityVo> tree = zyCommunityService.getCommunityAndBuildingTree();
        return new ResponseResult<>(ResponseStatus.OK, tree);
    }

    /**
     * 获取小区和楼栋和单元树
     * @return
     */
    @ApiOperation("查询小区楼栋单元树")
    @GetMapping("/listCommunityAndBuildingAndUnit")
    public ResponseResult<List<ZyCommunityVo>> getCommunityAndBuildingAndUnitTree(){
        List<ZyCommunityVo> tree = zyCommunityService.getCommunityAndBuildingAndUnitTree();
        return new ResponseResult<>(ResponseStatus.OK, tree);
    }



    @ApiOperation("新增小区信息")
    @PostMapping("/add")
    public ResponseResult<String> add(@RequestBody ZyCommunity zyCommunity) {
        zyCommunity.setCommunityCode(UUIDUtils.getCommunityCode());
        zyCommunity.setCreateTime(LocalDateTime.now());
        zyCommunityService.save(zyCommunity);
        return new ResponseResult<String>(ResponseStatus.OK, "新增小区成功");
    }

    @ApiOperation("修改小区信息")
    @PutMapping("/update")
    public ResponseResult<String> update(@RequestBody ZyCommunity zyCommunity) {
        zyCommunity.setUpdateTime(LocalDateTime.now());
        zyCommunityService.updateById(zyCommunity);
        return new ResponseResult<String>(ResponseStatus.OK, "修改小区成功");
    }

    @ApiOperation("删除小区信息")
    @DeleteMapping("/delete/{ids}")
    public ResponseResult<String> delete(@PathVariable List ids) {
        zyCommunityService.removeByIds(ids);
        return new ResponseResult<String>(ResponseStatus.OK, "删除小区成功");
    }

    /**
     * 导出当前页所有小区信息
     * @param response
     * @throws IOException
     */
    @ApiOperation("导出当前页所有小区信息")
    @GetMapping("/export")
    public void export(HttpServletResponse response, int curr, int size, String communityCode, String communityName) throws IOException {
        ExcelWriter writer= null;
        ServletOutputStream outputStream= null;
        try {
            //查询当前页面所有小区
            List<ZyCommunityVo> all = zyCommunityService.getCommunityPage(curr, size, communityCode, communityName).getRecords();

            //在内存操作，写到浏览器
            writer = ExcelUtil.getWriter(true);

            //自定义标题别名
            writer.addHeaderAlias("communityId", "小区id");
            writer.addHeaderAlias("communityName", "小区名称");
            writer.addHeaderAlias("communityCode", "小区编码");
            writer.addHeaderAlias("communityProvenceCode", "省");
            writer.addHeaderAlias("communityCityCode", "市区");
            writer.addHeaderAlias("communityTownCode", "区县");
            writer.addHeaderAlias("communityDetailedAddress", "详细地址");
            writer.addHeaderAlias("communityLongitude", "经度");
            writer.addHeaderAlias("communityLatitude", "纬度");
            writer.addHeaderAlias("communityCode", "物业id");
            writer.addHeaderAlias("createBy", "创建者");
            writer.addHeaderAlias("createTime", "创建时间");
            writer.addHeaderAlias("remark", "备注");

            //默认配置
            writer.write(all,true);
            // 设置只导出别名列
            writer.setOnlyAlias(true);
            //设置content—type
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset:utf-8");

            //设置标题
            String fileName= URLEncoder.encode("小区信息","UTF-8");
            //Content-disposition是MIME协议的扩展，MIME协议指示MIME用户代理如何显示附加的文件。
            response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //将Writer刷新到OutPut
            writer.flush(outputStream,true);
            outputStream.close();
            writer.close();
        }
    }


}

